#include "Poco/Net/SecureServerSocket.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Net/TCPServerConnection.h "
#include "Poco/Net/Context.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Thread.h"
// #include "Poco/Util/Application.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/HelpFormatter.h"
#include <iostream>

using namespace Poco;
using namespace Poco::Net;
using namespace Poco::Util;

class EchoConnection : public TCPServerConnection
{
public:
    EchoConnection(const StreamSocket& s) : TCPServerConnection(s) { }

    void run()
    {
        StreamSocket& ss = socket();
        try
        {
            char buffer[256];
            int n = ss.receiveBytes(buffer, sizeof(buffer));
            while (n > 0)
            {
                ss.sendBytes(buffer, n);
                n = ss.receiveBytes(buffer, sizeof(buffer));
            }
        }
        catch (Poco::Exception& exc)
        {
            std::cerr << "EchoConnection: " << exc.displayText() << std::endl;
        }
    }
};

class SSLServerApp : public ServerApplication
{
public:
    SSLServerApp() : _helpRequested(false) {}

    int main(const std::vector<std::string>& args)
    {
        if (_helpRequested)
        {
            displayHelp();
            return Application::EXIT_OK;
        }

        Context::Ptr context = new Context(Context::SERVER_USE, "key.pem", "certificate.pem", "", Context::VERIFY_NONE, 9, false);
        SSLManager::instance().initializeServer(0, 0, context);

        SecureServerSocket svs(9980);
        TCPServer srv(new TCPServerConnectionFactoryImpl<EchoConnection>(), svs);
        srv.start();
        
        std::cout << "SSL Echo Server started on port 9980" << std::endl;
        waitForTerminationRequest();

        std::cout << "Stopping Echo Server..." << std::endl;
        srv.stop();

        return Application::EXIT_OK;
    }

protected:
    void initialize(Application& self)
    {
        loadConfiguration();
        Application::initialize(self);
    }

    void uninitialize()
    {
        Application::uninitialize();
    }

    void defineOptions(OptionSet& options)
    {
        Application::defineOptions(options);

        options.addOption(
            Option("help", "h", "display help information")
            .required(false)
            .repeatable(false)
            .callback(OptionCallback<SSLServerApp>(this, &SSLServerApp::handleHelp)));
    }

    void handleHelp(const std::string& name, const std::string& value)
    {
        _helpRequested = true;
    }

    void displayHelp()
    {
        HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage("OPTIONS");
        helpFormatter.setHeader("A sample SSL echo server using the POCO C++ Libraries.");
        helpFormatter.format(std::cout);
    }

private:
    bool _helpRequested;
};

POCO_SERVER_MAIN(SSLServerApp)